#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QNetworkInterface>
#include <QJsonObject>
#include <QDebug>

class RobotClient;

class TcpServer : public QObject
{
    Q_OBJECT

public:
    explicit TcpServer(QObject *parent = nullptr);
    ~TcpServer();

    // 服务器控制
    bool startServer(int port = 8888);
    void stopServer();
    bool isRunning() const;
    
    // 服务器信息
    QString getServerAddress() const;
    int getServerPort() const;
    int getConnectedClientsCount() const;
    
    // 客户端管理
    RobotClient* findClientBySN(const QString &sn) const;
    QList<RobotClient*> getAllClients() const;
    bool disconnectRobotBySN(const QString &sn);

signals:
    void serverStarted(const QString &address, int port);
    void serverStopped();
    void clientConnected(const QString &address, int port);
    void clientDisconnected(const QString &address);
    void serverError(const QString &error);
    void robotRegistered(const QString &sn);
    void robotDataReceived(const QString &sn, const QJsonObject &data);
    void robotHeartbeatReceived(const QString &sn, const QJsonObject &data);
    void robotDisconnected(const QString &sn);
    void jsonParseError(const QString &clientIp, const QString &rawData, const QString &errorMsg);

private slots:
    void onNewConnection();
    void onClientDisconnected();

private:
    QTcpServer *m_server;
    QList<RobotClient*> m_clients;
    
    QString getLocalIPAddress() const;
};

#endif // TCPSERVER_H